package com.module.overview.ui.cardHistoryDetails.provider

import android.graphics.Typeface
import android.util.Log
import android.widget.TextView
import androidx.appcompat.widget.LinearLayoutCompat
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.CalendarDay
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.utils.AppUtils
import com.common.base.utils.JsonUtils
import com.common.base.utils.MathUtil
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.getColor
import com.common.base.utils.ViewUtils.getString
import com.module.ble.data.bean.CusChartData
import com.module.ble.db.table.UserAcLevel
import com.module.ble.db.table.UserCalorie
import com.module.ble.db.table.UserStepsRelatedRecord
import com.module.ble.repo.UserAcLevelRepo
import com.module.ble.repo.UserCalorieRepo
import com.module.ble.repo.UserStepsRelatedRecordRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.utils.common48DataConvertByAcLevelRelatedRecord
import com.module.ble.utils.common48DataConvertByCalorieRelatedRecord
import com.module.ble.utils.common48DataConvertByStepsRelatedRecord
import com.module.ble.utils.groupAcLevelDataByValueAndTime
import com.module.ble.widget.StressBrokenLineChart
import com.module.overview.R
import java.util.Calendar
import kotlin.math.absoluteValue

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/14
 *
 * 描述：活动总结卡片
 *
 * 修订历史：完成度80%
 *
 */
class OvActivitySummaryCardProvider(mCalendar: CalendarDay?,
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_ACTIVITY_SUMMARY,
    override val layoutId: Int = R.layout.overview_activity_summary_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    var mCalendar = mCalendar
    private var curTime = mCalendar?.toCalendar()?.timeInMillis?:0

    private var tvRelaxationDuration : TextView? = null
    private var tvTheDayDuration : TextView? = null
    private var tvWeeksDuration : TextView? = null

    private var llAcConsumptionCk: LinearLayoutCompat? = null
    private var llAcDurationCk : LinearLayoutCompat? = null
    private var llAcStrengthDurationCk : LinearLayoutCompat? = null
    private var llAcTotalScoreCk : LinearLayoutCompat? = null
    private var stressLineChart: StressBrokenLineChart? = null
    private var tvAcConsumptionHint : TextView? = null
    private var tvAcDurationHint : TextView? = null
    private var tvAcStrengthDurationHint : TextView? = null
    private var tvAcTotalScoreHint : TextView? = null
    private var tvAcConsumption : TextView? = null
    private var tvAcDuration : TextView? = null
    private var tvAcStrengthDuration : TextView? = null
    private var tvAcTotalScore : TextView? = null

    private val commonRailUnit = getString(R.string.common_rail_unit)

    // 根据timeRanges分类出每天的对应数据 - 使用List<Pair>格式
    private val perDayStepPairs = mutableListOf<Pair<Long, MutableList<UserStepsRelatedRecord>>>()
    private val perDayCaloriePairs = mutableListOf<Pair<Long, MutableList<UserCalorie>>>()

    // 7天的每天步数48个区间数据 - 使用List<Pair>格式
    private val sevenDaysStep48Pairs = mutableListOf<Pair<Long, MutableList<CusChartData>>>()

    val synthesisTheDayStep48AccumulationList = mutableListOf<CusChartData>()//当天数据叠加逻辑
    val synthesisSevenDaysStep48AccumulationList = mutableListOf<CusChartData>()//7天数据叠加逻辑

    val synthesisTheDayAcConsumption48AccumulationList = mutableListOf<CusChartData>()//当天数据叠加逻辑
    val synthesisSevenDaysAcConsumption48AccumulationList = mutableListOf<CusChartData>()//7天数据叠加逻辑

    private var synthesisTheDayStep48List = mutableListOf<CusChartData>()
    private var synthesisSevenDaysStep48List = mutableListOf<CusChartData>()

    var theDayAcConsumption = -1L//单天活动消耗，单位：千卡
    var theDayStepsNum = -1L//单天步数

    var sevenDaysAcConsumption = -1L//7天活动消耗，单位：千卡
    var sevenDaysStepsNum = -1L//7天步数

    val timeRanges by lazy { TimeUtils.getDayStartTimestamps(curTime, 6) }// 获取前7天的时间范围（含今天）

    var currentTime = TimeUtils.getTimeDateLong()//当前时间戳

    private val perDayAcLevelPairs = mutableListOf<Pair<Long, MutableList<UserAcLevel>>>()
    // 7天的每天步数48个区间数据 - 使用List<Pair>格式
    private val sevenDaysAcLevel48Pairs = mutableListOf<Pair<Long, MutableList<CusChartData>>>()
    private var synthesisTheDayAcLevel48List = mutableListOf<CusChartData>()
    private var synthesisSevenDaysAcLevel48List = mutableListOf<CusChartData>()
    val synthesisTheDayAcLevel48AccumulationList = mutableListOf<CusChartData>()//当天数据叠加逻辑
    val synthesisSevenDaysAcLevel48AccumulationList = mutableListOf<CusChartData>()//7天数据叠加逻辑
    var theDayAcLevelNum = -1L//单天步数
    var sevenDaysAcLevelNum = -1L//7天步数

    val synthesisTheDayAcStrengthDuration48AccumulationList = mutableListOf<CusChartData>()//当天数据叠加逻辑
    val synthesisSevenDaysAcStrengthDuration48AccumulationList = mutableListOf<CusChartData>()//7天数据叠加逻辑
    var theDayAcStrengthDurationNum = -1L//单天步数
    var sevenDaysAcStrengthDurationNum = -1L//7天步数

    init {
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {
        currentTime = TimeUtils.getTimeDateLong()

        stressLineChart?.setDashedLineEnabled(true)
        stressLineChart?.setRealTimeIndicatorEnabled(true)
        stressLineChart?.setTouchEnabled(false)

        // 在代码中设置数据
//        stressLineChart?.setStressData(stressData)
//        stressLineChart?.setBenchMarkingData(benchMarkingsData)

        // 设置触摸监听
        stressLineChart?.setOnStressPointTouchListener(object :
            StressBrokenLineChart.OnStressPointTouchListener{
            override fun onPointTouch(pointIndex: Int, value: Float, timeLabel: String) {
                // 处理触摸事件
                Log.d("StressChart", "时间: $timeLabel, 压力值: $value")
            }

        })

        tvWeeksDuration?.text = "${TimeUtils.getMonthDay(timeRanges[0])}-${TimeUtils.getMonthDay(timeRanges[6])}"

        getSevenDaysActivityData()

        getSevenDaysCalorieData()

        getSevenDaysAcLevelData()
    }


    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {

        tvRelaxationDuration = viewHolder.getView(R.id.tvRelaxationDuration)
        tvTheDayDuration = viewHolder.getView(R.id.tvTheDayDuration)
        tvWeeksDuration = viewHolder.getView(R.id.tvWeeksDuration)

        llAcConsumptionCk = viewHolder.getView(R.id.llAcConsumptionCk)
        llAcDurationCk = viewHolder.getView(R.id.llAcDurationCk)
        llAcStrengthDurationCk = viewHolder.getView(R.id.llAcStrengthDurationCk)
        llAcTotalScoreCk = viewHolder.getView(R.id.llAcTotalScoreCk)
        stressLineChart = viewHolder.getView(R.id.stressLineChart)

        tvAcConsumptionHint = viewHolder.getView(R.id.tvAcConsumptionHint)
        tvAcDurationHint = viewHolder.getView(R.id.tvAcDurationHint)
        tvAcStrengthDurationHint = viewHolder.getView(R.id.tvAcStrengthDurationHint)
        tvAcTotalScoreHint = viewHolder.getView(R.id.tvAcTotalScoreHint)

        tvAcConsumption = viewHolder.getView(R.id.tvAcConsumption)
        tvAcDuration = viewHolder.getView(R.id.tvAcDuration)
        tvAcStrengthDuration = viewHolder.getView(R.id.tvAcStrengthDuration)
        tvAcTotalScore = viewHolder.getView(R.id.tvAcTotalScore)

        llAcConsumptionCk?.let { viewIt ->
            viewIt.setOnClickListener {
                viewIt.isSelected.yes {
                    setAllPillarNotSelect()
                }.otherwise {
//                    initData()
//                    stressLineChart?.setStressData(stressData,benchMarkingsData)
                    setAllPillarNotSelect()
                    setAcConsumptionCkData(true)
                }
            }
        }

        llAcDurationCk?.let { viewIt ->
            viewIt.setOnClickListener {
                viewIt.isSelected.yes {
                    setAllPillarNotSelect()
                }.otherwise {
                    setAllPillarNotSelect()
                    setAcDurationCkData(true)
                }
            }
        }

        llAcStrengthDurationCk?.let { viewIt ->
            viewIt.setOnClickListener {
                viewIt.isSelected.yes {
                    setAllPillarNotSelect()
                }.otherwise {
                    setAllPillarNotSelect()
                    setAcStrengthDurationCkData(true)
                }
            }
        }

        llAcTotalScoreCk?.let { viewIt ->
            viewIt.setOnClickListener {
                viewIt.isSelected.yes {
                    setAllPillarNotSelect()
                }.otherwise {
                    setAllPillarNotSelect()
                    setAcTotalScoreCkData(true)
                }
            }
        }

        setAllPillarNotSelect()

        super.onViewHolderCreated(viewHolder, viewType)
    }

    fun changeDefUi(){
        tvTheDayDuration?.setTextColor(getColor(R.color.text_content))
        tvTheDayDuration?.text = "${if(mCalendar?.dateName == getString(R.string.common_today_hint)) getString(R.string.common_today_hint) else TimeUtils.getMonthDayMMdd(curTime)}(${TimeUtils.getHourMinute(TimeUtils.getTimeDateLong())})  $theDayStepsNum${getString(R.string.common_step_splice)}"
        tvWeeksDuration?.text = "${TimeUtils.getMonthDay(timeRanges[0])}-${TimeUtils.getMonthDay(timeRanges[6])}  $sevenDaysStepsNum${getString(R.string.common_step_splice)}"

        val diff = theDayStepsNum - sevenDaysStepsNum
        when {
            diff > 0L -> {//大于
                tvRelaxationDuration?.let { viewIt ->
                    SpanUtils.create()
                        .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                        .addSection("${getString(R.string.overview_activity_steps_num_hint3)}")
                        .addSection(getString(R.string.overview_sleep_summary_pd_increase_hint))
                        .addSection(diff.toString())
                        .addSection(getString(R.string.common_step_splice))
                        .showIn(viewIt)
                }
            }
            diff == 0L-> {//等于
                tvRelaxationDuration?.text = "${getString(R.string.overview_sleep_summary_pd_hint)}${getString(R.string.overview_activity_steps_num_hint3)}${getString(R.string.overview_sleep_summary_pd_hint2)}"
            }
            else -> {//小于
                tvRelaxationDuration?.let { viewIt ->
                    SpanUtils.create()
                        .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                        .addSection("${getString(R.string.overview_activity_steps_num_hint3)}")
                        .addSection(getString(R.string.overview_sleep_summary_pd_reduce_hint))
                        .addSection(diff.absoluteValue.toString())
                        .addSection(getString(R.string.common_step_splice))
                        .showIn(viewIt)
                }
            }
        }

        stressLineChart?.setStressData(synthesisSevenDaysStep48AccumulationList,synthesisTheDayStep48AccumulationList)
    }

    private fun setAllPillarNotSelect(){

        setAcConsumptionCkData()
        setAcDurationCkData()
        setAcStrengthDurationCkData()
        setAcTotalScoreCkData()
        llAcConsumptionCk?.isSelected = false
        llAcDurationCk?.isSelected = false
        llAcStrengthDurationCk?.isSelected = false
        llAcTotalScoreCk?.isSelected = false
        stressLineChart?.setSelectType(-1)

        changeDefUi()
    }

    fun setAcConsumptionCkData(isSelect: Boolean =false){//活动消耗
        val tvLastStr = if(theDayAcConsumption >=0) theDayAcConsumption.toString() else commonRailUnit

        tvAcConsumptionHint?.setTextColor(if (isSelect) getColor(R.color.c_ff8a7f) else getColor(R.color.c_7f7f7f))
        tvAcConsumption?.let { viewIt ->
            viewIt.setTextColor(if (isSelect) getColor(R.color.c_ff8a7f) else getColor(R.color.c_7f7f7f))
            SpanUtils.create()
                .addForeColorSection(
                    tvLastStr,
                    if (isSelect) getColor(R.color.c_ff8a7f) else getColor(R.color.text_content)
                )
                .setAbsSize(tvLastStr, 16)
                .setStyle(tvLastStr, Typeface.BOLD)
                .addSection("${getString(R.string.common_calorie_splice)}")
                .showIn(viewIt)
        }
        isSelect.yes {
            tvTheDayDuration?.setTextColor(getColor(R.color.c_ff8a7f))
            tvTheDayDuration?.text = "${getString(R.string.common_today_hint)}(${TimeUtils.getHourMinute(TimeUtils.getTimeDateLong())})  $theDayAcConsumption${getString(R.string.common_calorie_splice)}"
            tvWeeksDuration?.text = "${TimeUtils.getMonthDay(timeRanges[0])}-${TimeUtils.getMonthDay(timeRanges[6])}  $sevenDaysAcConsumption${getString(R.string.common_calorie_splice)}"

            val diff = theDayAcConsumption - sevenDaysAcConsumption
            when {
                diff > 0L -> {//大于
                    tvRelaxationDuration?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_activity_consumption_hint)}",
                                getColor(R.color.c_ff8a7f)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_increase_hint))
                            .addSection(diff.toString())
                            .addSection(getString(R.string.common_calorie_splice))
                            .showIn(viewIt)
                    }
                }
                diff == 0L-> {//等于
                    tvRelaxationDuration?.text = "${getString(R.string.overview_sleep_summary_pd_hint)}${getString(R.string.overview_activity_consumption_hint)}${getString(R.string.overview_sleep_summary_pd_hint2)}"
                }
                else -> {//小于
                    tvRelaxationDuration?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_activity_consumption_hint)}",
                                getColor(R.color.c_ff8a7f)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_reduce_hint))
                            .addSection(diff.absoluteValue.toString())
                            .addSection(getString(R.string.common_calorie_splice))
                            .showIn(viewIt)
                    }
                }
            }

            stressLineChart?.setStressData(synthesisSevenDaysAcConsumption48AccumulationList,synthesisTheDayAcConsumption48AccumulationList)

            llAcConsumptionCk?.isSelected = true
        }
    }

    fun setAcDurationCkData(isSelect: Boolean =false){

        val theDayAcLevelNumList = TimeUtils.formatTimeToList(theDayAcLevelNum*60*1000)

        tvAcDurationHint?.setTextColor(if (isSelect) getColor(R.color.c_ff8a7f) else getColor(R.color.c_7f7f7f))
        tvAcDuration?.let { viewIt ->
            viewIt.setTextColor(if (isSelect) getColor(R.color.c_ff8a7f) else getColor(R.color.c_7f7f7f))

            val spanBuilderTemp = SpanUtils.create()
            (theDayAcLevelNumList[1]>0).yes {
                spanBuilderTemp
                    .addSection( if(theDayAcLevelNum >=0) theDayAcLevelNumList[1].toString() else commonRailUnit)
                    .setAbsSize(if(theDayAcLevelNum >=0) theDayAcLevelNumList[1].toString() else commonRailUnit, 16)
                    .setStyle(if(theDayAcLevelNum >=0) theDayAcLevelNumList[1].toString() else commonRailUnit, Typeface.BOLD)
                    .addSection(AppUtils.getString(R.string.common_hours_hint))
                    .setAbsSize(AppUtils.getString(R.string.common_hours_hint), 12)
                    .setStyle(AppUtils.getString(R.string.common_hours_hint), Typeface.NORMAL)
            }

            spanBuilderTemp
                .addSection(if(theDayAcLevelNum >=0) theDayAcLevelNumList[2].toString() else commonRailUnit)
                .setAbsSize(if(theDayAcLevelNum >=0) theDayAcLevelNumList[2].toString() else commonRailUnit, 16)
                .setStyle(if(theDayAcLevelNum >=0) theDayAcLevelNumList[2].toString() else commonRailUnit, Typeface.BOLD)
                .addSection(AppUtils.getString(R.string.common_minutes_hint))
                .setAbsSize(AppUtils.getString(R.string.common_minutes_hint), 12)
                .setStyle(AppUtils.getString(R.string.common_minutes_hint), Typeface.NORMAL)
                .showIn(viewIt)
        }

        isSelect.yes {
            tvTheDayDuration?.setTextColor(getColor(R.color.c_ff8a7f))
            tvTheDayDuration?.text = "${getString(R.string.common_today_hint)}(${TimeUtils.getHourMinute(TimeUtils.getTimeDateLong())})  ${TimeUtils.formatTime(theDayAcLevelNum*60*1000, showHour = true, showMin = true)}"
            tvWeeksDuration?.text = "${TimeUtils.getMonthDay(timeRanges[0])}-${TimeUtils.getMonthDay(timeRanges[6])}  ${TimeUtils.formatTime(sevenDaysAcLevelNum*60*1000, showHour = true, showMin = true)}"

            val diff = theDayAcLevelNum - sevenDaysAcLevelNum
            when {
                diff > 0L -> {//大于
                    tvRelaxationDuration?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_activity_steps_num_hint3)}",
                                getColor(R.color.c_ff8a7f)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_increase_hint))
                            .addSection(TimeUtils.formatTime(diff*60*1000, showHour = true, showMin = true))
                            .addSection(getString(R.string.overview_step_splice))
                            .showIn(viewIt)
                    }
                }
                diff == 0L-> {//等于
                    tvRelaxationDuration?.text = "${getString(R.string.overview_sleep_summary_pd_hint)}${getString(R.string.overview_activity_steps_num_hint3)}${getString(R.string.overview_sleep_summary_pd_hint2)}"
                }
                else -> {//小于
                    tvRelaxationDuration?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_activity_steps_num_hint3)}",
                                getColor(R.color.c_ff8a7f)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_reduce_hint))
                            .addSection(TimeUtils.formatTime(diff.absoluteValue*60*1000, showHour = true, showMin = true))
                            .addSection(getString(R.string.overview_step_splice))
                            .showIn(viewIt)
                    }
                }
            }

            stressLineChart?.setStressData(synthesisSevenDaysAcStrengthDuration48AccumulationList,synthesisTheDayAcStrengthDuration48AccumulationList)
            llAcDurationCk?.isSelected = true
        }
    }

    fun setAcStrengthDurationCkData(isSelect: Boolean =false){
        val theDayAcStrengthDurationNumList = TimeUtils.formatTimeToList(theDayAcStrengthDurationNum*60*1000)

        tvAcStrengthDurationHint?.setTextColor(if (isSelect) getColor(R.color.c_ff8a7f) else getColor(R.color.c_7f7f7f))
        tvAcStrengthDuration?.let { viewIt ->
            viewIt.setTextColor(if (isSelect) getColor(R.color.c_ff8a7f) else getColor(R.color.c_7f7f7f))

            val spanBuilderTemp = SpanUtils.create()
            (theDayAcStrengthDurationNumList[1]>0).yes {
                spanBuilderTemp
                    .addSection( if(theDayAcStrengthDurationNum >=0) theDayAcStrengthDurationNumList[1].toString() else commonRailUnit)
                    .setAbsSize(if(theDayAcStrengthDurationNum >=0) theDayAcStrengthDurationNumList[1].toString() else commonRailUnit, 16)
                    .setStyle(if(theDayAcStrengthDurationNum >=0) theDayAcStrengthDurationNumList[1].toString() else commonRailUnit, Typeface.BOLD)
                    .addSection(AppUtils.getString(R.string.common_hours_hint))
                    .setAbsSize(AppUtils.getString(R.string.common_hours_hint), 12)
                    .setStyle(AppUtils.getString(R.string.common_hours_hint), Typeface.NORMAL)
            }

            spanBuilderTemp
                .addSection(if(theDayAcStrengthDurationNum >=0) theDayAcStrengthDurationNumList[2].toString() else commonRailUnit)
                .setAbsSize(if(theDayAcStrengthDurationNum >=0) theDayAcStrengthDurationNumList[2].toString() else commonRailUnit, 16)
                .setStyle(if(theDayAcStrengthDurationNum >=0) theDayAcStrengthDurationNumList[2].toString() else commonRailUnit, Typeface.BOLD)
                .addSection(AppUtils.getString(R.string.common_minutes_hint))
                .setAbsSize(AppUtils.getString(R.string.common_minutes_hint), 12)
                .setStyle(AppUtils.getString(R.string.common_minutes_hint), Typeface.NORMAL)
                .showIn(viewIt)
        }

        isSelect.yes {
            tvTheDayDuration?.setTextColor(getColor(R.color.c_ff8a7f))
            tvTheDayDuration?.text = "${getString(R.string.common_today_hint)}(${TimeUtils.getHourMinute(TimeUtils.getTimeDateLong())})  ${TimeUtils.formatTime(theDayAcStrengthDurationNum*60*1000, showHour = true, showMin = true)}"
            tvWeeksDuration?.text = "${TimeUtils.getMonthDay(timeRanges[0])}-${TimeUtils.getMonthDay(timeRanges[6])}  ${TimeUtils.formatTime(sevenDaysAcStrengthDurationNum*60*1000, showHour = true, showMin = true)}"

            val diff = theDayAcStrengthDurationNum - sevenDaysAcStrengthDurationNum
            when {
                diff > 0L -> {//大于
                    tvRelaxationDuration?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_activity_steps_num_hint3)}",
                                getColor(R.color.c_ff8a7f)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_increase_hint))
                            .addSection(TimeUtils.formatTime(diff*60*1000, showHour = true, showMin = true))
                            .addSection(getString(R.string.overview_step_splice))
                            .showIn(viewIt)
                    }
                }
                diff == 0L-> {//等于
                    tvRelaxationDuration?.text = "${getString(R.string.overview_sleep_summary_pd_hint)}${getString(R.string.overview_activity_steps_num_hint3)}${getString(R.string.overview_sleep_summary_pd_hint2)}"
                }
                else -> {//小于
                    tvRelaxationDuration?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_activity_steps_num_hint3)}",
                                getColor(R.color.c_ff8a7f)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_reduce_hint))
                            .addSection(TimeUtils.formatTime(diff.absoluteValue*60*1000, showHour = true, showMin = true))
                            .addSection(getString(R.string.overview_step_splice))
                            .showIn(viewIt)
                    }
                }
            }

            stressLineChart?.setStressData(synthesisSevenDaysAcLevel48AccumulationList,synthesisTheDayAcLevel48AccumulationList)
            llAcStrengthDurationCk?.isSelected = true
        }
    }

    fun setAcTotalScoreCkData(isSelect: Boolean =false){
        val tvLastStr = if(theDayStepsNum >=0) sevenDaysStepsNum.toString() else commonRailUnit

        tvAcTotalScoreHint?.setTextColor(if (isSelect) getColor(R.color.c_ff8a7f) else getColor(R.color.c_7f7f7f))
        tvAcTotalScore?.let { viewIt ->
            viewIt.setTextColor(if (isSelect) getColor(R.color.c_ff8a7f) else getColor(R.color.c_7f7f7f))
            SpanUtils.create()
                .addForeColorSection(
                    tvLastStr,
                    if (isSelect) getColor(R.color.c_ff8a7f) else getColor(R.color.text_content)
                )
                .setAbsSize(tvLastStr, 16)
                .setStyle(tvLastStr, Typeface.BOLD)
                .addSection("${getString(R.string.overview_step_splice)}")
                .showIn(viewIt)
        }

        isSelect.yes {
            tvTheDayDuration?.setTextColor(getColor(R.color.c_ff8a7f))
            tvTheDayDuration?.text = "${getString(R.string.common_today_hint)}(${TimeUtils.getHourMinute(TimeUtils.getTimeDateLong())})  $theDayStepsNum${getString(R.string.overview_step_splice)}"
            tvWeeksDuration?.text = "${TimeUtils.getMonthDay(timeRanges[0])}-${TimeUtils.getMonthDay(timeRanges[6])}  $sevenDaysStepsNum${getString(R.string.overview_step_splice)}"

            val diff = theDayStepsNum - sevenDaysStepsNum
            when {
                diff > 0L -> {//大于
                    tvRelaxationDuration?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_activity_steps_num_hint3)}",
                                getColor(R.color.c_ff8a7f)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_increase_hint))
                            .addSection(diff.toString())
                            .addSection(getString(R.string.overview_step_splice))
                            .showIn(viewIt)
                    }
                }
                diff == 0L-> {//等于
                    tvRelaxationDuration?.text = "${getString(R.string.overview_sleep_summary_pd_hint)}${getString(R.string.overview_activity_steps_num_hint3)}${getString(R.string.overview_sleep_summary_pd_hint2)}"
                }
                else -> {//小于
                    tvRelaxationDuration?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_activity_steps_num_hint3)}",
                                getColor(R.color.c_ff8a7f)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_reduce_hint))
                            .addSection(diff.absoluteValue.toString())
                            .addSection(getString(R.string.overview_step_splice))
                            .showIn(viewIt)
                    }
                }
            }

            stressLineChart?.setStressData(synthesisSevenDaysStep48AccumulationList,synthesisTheDayStep48AccumulationList)
            llAcTotalScoreCk?.isSelected = true
        }
    }

    /**
     * 获取7天活动信息
     */
    fun getSevenDaysActivityData(){
        if (curTime <=0) return

        UserStepsRelatedRecordRepo.instance.findByMultiTimeRanges(timeRanges)?.let { originalListIt->
            if (originalListIt.isNullOrEmpty()) return

//                val listItStr = JsonUtils.toJson(originalListIt)

            perDayStepPairs.clear()
            // 初始化每天的数据列表
            timeRanges.forEach { dayTimestamp ->
                perDayStepPairs.add(Pair(dayTimestamp, mutableListOf()))
            }

            // 将数据分类到对应的天
            originalListIt.forEach { record ->
                perDayStepPairs.forEachIndexed { index, (dayTimestamp, dayRecords) ->
                    val dayEnd = dayTimestamp + 24 * 60 * 60 * 1000 - 1 // 当天23:59:59.999

                    if (record.createdTime in dayTimestamp..dayEnd) {
                        dayRecords.add(record)
                        return@forEach // 找到对应天后跳出循环
                    }
                }
            }

            calculateStepAndCalorieClassData()
            changeDefUi()
            calculateStepAndCalorieClassData(1)
            setAcConsumptionCkData()
            setAcTotalScoreCkData(false)
        }
    }


    /**
     * 获取7天卡路里信息
     */
    fun getSevenDaysCalorieData(){
        if (curTime <=0) return

        UserCalorieRepo.instance.findByMultiTimeRanges(timeRanges)?.let { originalListIt->
            if (originalListIt.isNullOrEmpty()) return

//                val listItStr = JsonUtils.toJson(originalListIt)

            perDayCaloriePairs.clear()
            // 初始化每天的数据列表
            timeRanges.forEach { dayTimestamp ->
                perDayCaloriePairs.add(Pair(dayTimestamp, mutableListOf()))
            }

            // 将数据分类到对应的天
            originalListIt.forEach { record ->
                perDayCaloriePairs.forEachIndexed { index, (dayTimestamp, dayRecords) ->
                    val dayEnd = dayTimestamp + 24 * 60 * 60 * 1000 - 1 // 当天23:59:59.999

                    if (record.createdTime in dayTimestamp..dayEnd) {
                        dayRecords.add(record)
                        return@forEach // 找到对应天后跳出循环
                    }
                }
            }

            calculateStepAndCalorieClassData()
            changeDefUi()
            calculateStepAndCalorieClassData(1)
            setAcConsumptionCkData()
        }
    }


    fun calculateStepAndCalorieClassData(mType:Int=0){
        (mType == 1).yes{
            if (perDayCaloriePairs.isNullOrEmpty()) return
        }.otherwise {
            if (perDayStepPairs.isNullOrEmpty()) return
        }

        val curTimePointIndex = calculateCurrentTimePointIndex()

        sevenDaysStep48Pairs.clear()

        (mType == 1).yes{
            perDayCaloriePairs.forEach {perDayPairsIt->
                sevenDaysStep48Pairs.add(Pair(perDayPairsIt.first, (common48DataConvertByCalorieRelatedRecord(doSum = true, curTime = perDayPairsIt.first, originalList = perDayPairsIt.second).toMutableList())))
            }
        }.otherwise {
            perDayStepPairs.forEach {perDayPairsIt->
                sevenDaysStep48Pairs.add(Pair(perDayPairsIt.first, (common48DataConvertByStepsRelatedRecord(mType = mType, doSum = true, curTime = perDayPairsIt.first, originalList = perDayPairsIt.second).toMutableList())))
            }
        }

        //取7天里第一条的second就是当天数据
        synthesisTheDayStep48List.clear()
        sevenDaysStep48Pairs.isNullOrEmpty().no {
            synthesisTheDayStep48List.addAll(sevenDaysStep48Pairs[0].second)
        }

        sevenDaysStep48Pairs.sortByDescending { it.first }//按时间排序（降序）
//        val sevenDaysStep48PairsStr = JsonUtils.toJson(sevenDaysStep48Pairs)

        // 初始化synthesisDayStep48List，创建48个时间区间的CusChartData
        synthesisSevenDaysStep48List.clear()
        if (sevenDaysStep48Pairs.isNotEmpty()) {
            // 获取第一天的数据作为模板，确定有多少个时间区间（通常是48个）
            val templateList = sevenDaysStep48Pairs.firstOrNull()?.second
            templateList?.let { template ->
                // 为每个时间区间创建汇总数据
                for (index in template.indices) {
                    var totalValue = 0f
                    var totalCount = 0

                    // 遍历所有天的数据，累加对应下标的mValue
                    sevenDaysStep48Pairs.forEach { dayPair ->
                        val dayData = dayPair.second
                        if (index < dayData.size) {
                            totalValue += dayData[index].mValue
                            totalCount++
                        }
                    }

                    // 创建汇总的CusChartData，使用第一天对应时间区间的时间信息作为模板
                    val templateData = template[index]
                    synthesisSevenDaysStep48List.add(
                        CusChartData(
                            createdTime = templateData.createdTime,
                            endTime = templateData.endTime,
                            mValue = totalValue, // 所有天对应时间区间的总和
                            minValue = 0f,
                            dayNum = templateData.dayNum,
                            exStr = totalValue.toInt().toString()
                        )
                    )
                }
            }
        }
        synthesisSevenDaysAcLevel48List.sortBy { it.createdTime }//保证升序排列
        val synthesisDayStep48ListStr = JsonUtils.toJson(synthesisSevenDaysStep48List)

        //叠加前先算出7天当前时间前的总和值
        if (synthesisSevenDaysStep48List.isNotEmpty()) {
//            for (i in synthesisSevenDaysStep48List.indices) {
//                // 如果当前数据的创建时间大于等于当前时间，则跳过该条数据
//                if (synthesisTheDayStep48List[i].createdTime >= currentTime) {
//                    continue
//                }
//
//                (mType == 1).yes{
//                    sevenDaysAcConsumption += synthesisSevenDaysStep48List[i].mValue.toInt()
//                }.otherwise {
//                    sevenDaysStepsNum += synthesisSevenDaysStep48List[i].mValue.toInt()
//                }
//            }

            (mType == 1).yes{
                sevenDaysAcConsumption = if (synthesisSevenDaysStep48List.isNotEmpty() && curTimePointIndex > 0) {
                    synthesisSevenDaysStep48List.subList(0, curTimePointIndex)
//                        .filter { it.mValue >= 0 } // 过滤掉无效值
                        .takeIf { it.isNotEmpty() }
                        ?.map { it.mValue }
                        ?.sum()
                        ?.toLong() ?: 0
                } else {
                    0
                }
            }.otherwise {
                sevenDaysStepsNum = if (synthesisSevenDaysStep48List.isNotEmpty() && curTimePointIndex > 0) {
                    synthesisSevenDaysStep48List.subList(0, curTimePointIndex)
//                        .filter { it.mValue >= 0 } // 过滤掉无效值
                        .takeIf { it.isNotEmpty() }
                        ?.map { it.mValue }
                        ?.sum()
                        ?.toLong() ?: 0
                } else {
                    0
                }
            }
        }

        //7天数据叠加逻辑
        synthesisSevenDaysStep48List.sortByDescending { it.createdTime }//先降序排列
        val synthesisSevenDaysStep48AccumulationListTemp = mutableListOf<CusChartData>()
        if (synthesisSevenDaysStep48List.isNotEmpty()) {
            for (i in synthesisSevenDaysStep48List.indices) {
                // 计算从当前位置到列表末尾所有mValue的总和
                var accumulationValue = 0f
                for (j in i until synthesisSevenDaysStep48List.size) {
                    accumulationValue += synthesisSevenDaysStep48List[j].mValue
                }

                // 创建累积数据，使用当前位置的数据作为模板
                val templateData = synthesisSevenDaysStep48List[i]
                synthesisSevenDaysStep48AccumulationListTemp.add(
                    CusChartData(
                        createdTime = templateData.createdTime,
                        endTime = templateData.endTime,
                        mValue = accumulationValue, // 当前位置及后面所有数据的mValue总和
                        minValue = templateData.minValue,
                        dayNum = templateData.dayNum,
                        exStr = accumulationValue.toInt().toString()
                    )
                )
            }
        }

        synthesisSevenDaysStep48AccumulationListTemp.sortBy { it.createdTime }//还原为升序排列
//        val synthesisSevenDaysStep48AccumulationListStr = JsonUtils.toJson(synthesisSevenDaysStep48AccumulationList)

        //叠加前先算出总和值
//        (mType == 1).yes{
//            theDayAcConsumption = synthesisTheDayStep48List.sumOf { it.mValue.toInt()}.toLong()
//        }.otherwise {
//            theDayStepsNum = synthesisTheDayStep48List.sumOf { it.mValue.toInt()}.toLong()
//        }

        //叠加前先算出总和值
        (mType == 1).yes{
            theDayAcConsumption = if (synthesisTheDayStep48List.isNotEmpty() && curTimePointIndex > 0) {
                synthesisTheDayStep48List.subList(0, curTimePointIndex)
//                        .filter { it.mValue >= 0 } // 过滤掉无效值
                    .takeIf { it.isNotEmpty() }
                    ?.map { it.mValue }
                    ?.sum()
                    ?.toLong() ?: 0
            } else {
                0
            }
        }.otherwise {
            theDayStepsNum = if (synthesisTheDayStep48List.isNotEmpty() && curTimePointIndex > 0) {
                synthesisTheDayStep48List.subList(0, curTimePointIndex)
//                        .filter { it.mValue >= 0 } // 过滤掉无效值
                    .takeIf { it.isNotEmpty() }
                    ?.map { it.mValue }
                    ?.sum()
                    ?.toLong() ?: 0
            } else {
                0
            }
        }

        val synthesisTheDayStep48ListStr = JsonUtils.toJson(synthesisTheDayStep48List)

        //当天数据叠加逻辑
        synthesisTheDayStep48List.sortByDescending { it.createdTime }//按时间排序（降序）
        val synthesisTheDayStep48AccumulationListTemp = mutableListOf<CusChartData>()

        if (synthesisTheDayStep48List.isNotEmpty()) {
            for (i in synthesisTheDayStep48List.indices) {
                // 如果当前数据的创建时间大于等于当前时间，则跳过该条数据
                if (synthesisTheDayStep48List[i].createdTime >= currentTime) {
                    synthesisTheDayStep48AccumulationListTemp.add(
                        CusChartData(
                            createdTime = synthesisTheDayStep48List[i].createdTime,
                            endTime = synthesisTheDayStep48List[i].endTime,
                            mValue = -1.0f, // 当前位置及后面所有数据的mValue总和
                            minValue = synthesisTheDayStep48List[i].minValue,
                            dayNum = synthesisTheDayStep48List[i].dayNum,
                            exStr = "-1.0"
                        )
                    )
                    continue
                }
                // 计算从当前位置到列表末尾所有mValue的总和
                var accumulationValue = 0f
                for (j in i until synthesisTheDayStep48List.size) {
                    accumulationValue += synthesisTheDayStep48List[j].mValue
                }

                // 创建累积数据，使用当前位置的数据作为模板
                val templateData = synthesisTheDayStep48List[i]
                synthesisTheDayStep48AccumulationListTemp.add(
                    CusChartData(
                        createdTime = templateData.createdTime,
                        endTime = templateData.endTime,
                        mValue = accumulationValue, // 当前位置及后面所有数据的mValue总和
                        minValue = templateData.minValue,
                        dayNum = templateData.dayNum,
                        exStr = accumulationValue.toInt().toString()
                    )
                )
            }
        }
        synthesisTheDayStep48AccumulationListTemp.sortBy { it.createdTime }//还原为升序排列
        val synthesisTheDayStep48AccumulationListStr = JsonUtils.toJson(synthesisTheDayStep48AccumulationListTemp)

        //有效天数
        var validDays = 0

        // 遍历sevenDaysStep48Pairs，检查每天的数据
        sevenDaysStep48Pairs.forEach { dayPair ->
            val dayData = dayPair.second // 获取当天的List<CusChartData>

            // 检查当天是否有任意一个CusChartData的mValue大于0
            val hasAnyValueGreaterThanZero = dayData.isNotEmpty() && dayData.any { it.mValue > 0 }

            if (hasAnyValueGreaterThanZero) {
                validDays++
            }
        }

        //7天数据区间再除以有效天数均化
        synthesisSevenDaysStep48AccumulationListTemp.forEach {beanIt->
            beanIt.mValue = MathUtil.div(beanIt.mValue.toString(), validDays.toString(),false).toFloat()
        }

        //7天数据再除以有效天数均化
        sevenDaysAcConsumption = MathUtil.div(synthesisSevenDaysStep48List.sumOf { it.mValue.toInt()}.toString(),validDays.toString(),false).toFloat().toLong()

        //获取当天和7天里的最大值
        val synthesisTheDayMaxTemp = ((synthesisTheDayStep48AccumulationListTemp.maxOfOrNull { it.mValue } ?: 100f).toFloat())+20f
        val synthesisSevenDaysMaxTemp = ((synthesisSevenDaysStep48AccumulationListTemp.maxOfOrNull { it.mValue } ?: 100f).toFloat())+20f
        synthesisTheDayStep48AccumulationListTemp.forEach { theDayBeanIt->
            (theDayBeanIt.mValue>0).yes { theDayBeanIt.mValue = (MathUtil.div(theDayBeanIt.mValue.toString(),(if (synthesisSevenDaysMaxTemp>synthesisTheDayMaxTemp) synthesisSevenDaysMaxTemp else synthesisTheDayMaxTemp).toString(),false).toFloat() * 100) }
        }
        synthesisSevenDaysStep48AccumulationListTemp.forEach { sevenDaysBeanIt->
            sevenDaysBeanIt.mValue = (MathUtil.div(sevenDaysBeanIt.mValue.toString(),(if (synthesisSevenDaysMaxTemp>synthesisTheDayMaxTemp) synthesisSevenDaysMaxTemp else synthesisTheDayMaxTemp).toString(),false).toFloat() * 100)
        }

        val synthesisTheDayStep48AccumulationListStr2 = JsonUtils.toJson(synthesisTheDayStep48AccumulationListTemp)
        val synthesisSevenDaysStep48AccumulationListStr2 = JsonUtils.toJson(synthesisSevenDaysStep48AccumulationListTemp)

        (mType == 1).yes{
            synthesisTheDayAcConsumption48AccumulationList.clear()
            synthesisTheDayAcConsumption48AccumulationList.addAll(synthesisTheDayStep48AccumulationListTemp)
            synthesisSevenDaysAcConsumption48AccumulationList.clear()
            synthesisSevenDaysAcConsumption48AccumulationList.addAll(synthesisSevenDaysStep48AccumulationListTemp)
        }.otherwise {
            synthesisTheDayStep48AccumulationList.clear()
            synthesisTheDayStep48AccumulationList.addAll(synthesisTheDayStep48AccumulationListTemp)
            synthesisSevenDaysStep48AccumulationList.clear()
            synthesisSevenDaysStep48AccumulationList.addAll(synthesisSevenDaysStep48AccumulationListTemp)
        }
    }


    /**
     * 获取7天活动强度信息
     */
    fun getSevenDaysAcLevelData(){
        if (curTime <=0) return

        doOnIOThread {
            UserAcLevelRepo.instance.findByMultiTimeRanges(timeRanges)?.let { originalListIt->
                //测试数据
//                val originalListIt :List<UserAcLevel> = JsonUtils.fromJsonList("[{\"createdTime\":1759334460000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759334460000,\"acLevel\":73},{\"createdTime\":1759335240000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759335240000,\"acLevel\":80},{\"createdTime\":1759335300000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759335300000,\"acLevel\":43},{\"createdTime\":1759335360000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759335360000,\"acLevel\":46},{\"createdTime\":1759339020000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759339020000,\"acLevel\":51},{\"createdTime\":1759339080000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759339080000,\"acLevel\":52},{\"createdTime\":1759340280000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759340280000,\"acLevel\":55},{\"createdTime\":1759342860000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759342860000,\"acLevel\":86},{\"createdTime\":1759344660000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759344660000,\"acLevel\":83},{\"createdTime\":1759348260000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759348260000,\"acLevel\":90},{\"createdTime\":1759348860000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759348860000,\"acLevel\":20},{\"createdTime\":1759380120000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759380120000,\"acLevel\":52}]")

                if (originalListIt.isNullOrEmpty()) return@doOnIOThread

//                val listItStr = JsonUtils.toJson(originalListIt)

                perDayAcLevelPairs.clear()
                // 初始化每天的数据列表
                timeRanges.forEach { dayTimestamp ->
                    perDayAcLevelPairs.add(Pair(dayTimestamp, mutableListOf()))
                }

                // 将数据分类到对应的天
                originalListIt.forEach { record ->
                    perDayAcLevelPairs.forEachIndexed { index, (dayTimestamp, dayRecords) ->
                        val dayEnd = dayTimestamp + 24 * 60 * 60 * 1000 - 1 // 当天23:59:59.999

                        if (record.createdTime in dayTimestamp..dayEnd) {
                            dayRecords.add(record)
                            return@forEach // 找到对应天后跳出循环
                        }
                    }
                }

                calculateAcLevelClassData()
                doOnUiThread {
                    changeDefUi()
                    setAcDurationCkData(false)
                }

                calculateAcLevelClassData(60)

                doOnUiThread { setAcStrengthDurationCkData(false) }

            }
        }
    }



    fun calculateAcLevelClassData(minValue:Int = 0){
        if (perDayAcLevelPairs.isNullOrEmpty()) return

        val curTimePointIndex = calculateCurrentTimePointIndex()

        sevenDaysAcLevel48Pairs.clear()

        perDayAcLevelPairs.forEach {perDayPairsIt->
            sevenDaysAcLevel48Pairs.add(Pair(perDayPairsIt.first, (common48DataConvertByAcLevelRelatedRecord(curTime = perDayPairsIt.first, originalList = perDayPairsIt.second, minValue = minValue).toMutableList())))
        }

        //取7天里第一条的second就是当天数据
        synthesisTheDayAcLevel48List.clear()
        sevenDaysAcLevel48Pairs.isNullOrEmpty().no {
            synthesisTheDayAcLevel48List.addAll(sevenDaysAcLevel48Pairs[0].second)
        }

        sevenDaysAcLevel48Pairs.sortByDescending { it.first }//按时间排序（降序）
//        val sevenDaysAcLevel48PairsStr = JsonUtils.toJson(sevenDaysAcLevel48Pairs)

        // 初始化synthesisDayAcLevel48List，创建48个时间区间的CusChartData
        synthesisSevenDaysAcLevel48List.clear()
        if (sevenDaysAcLevel48Pairs.isNotEmpty()) {
            // 获取第一天的数据作为模板，确定有多少个时间区间（通常是48个）
            val templateList = sevenDaysAcLevel48Pairs.firstOrNull()?.second
            templateList?.let { template ->
                // 为每个时间区间创建汇总数据
                for (index in template.indices) {
                    var totalValue = 0f
                    var totalCount = 0

                    // 遍历所有天的数据，累加对应下标的mValue
                    sevenDaysAcLevel48Pairs.forEach { dayPair ->
                        val dayData = dayPair.second
                        if (index < dayData.size) {
                            totalValue += dayData[index].mValue
                            totalCount++
                        }
                    }

                    // 创建汇总的CusChartData，使用第一天对应时间区间的时间信息作为模板
                    val templateData = template[index]
                    synthesisSevenDaysAcLevel48List.add(
                        CusChartData(
                            createdTime = templateData.createdTime,
                            endTime = templateData.endTime,
                            mValue = totalValue, // 所有天对应时间区间的总和
                            minValue = 0f,
                            dayNum = templateData.dayNum,
                            exStr = totalValue.toInt().toString()
                        )
                    )
                }
            }
        }
        synthesisSevenDaysAcLevel48List.sortBy { it.createdTime }//保证升序排列
        val synthesisDayAcLevel48ListStr = JsonUtils.toJson(synthesisSevenDaysAcLevel48List)

        //叠加前先算出7天当前时间前的总和值
        if (synthesisSevenDaysAcLevel48List.isNotEmpty()) {

            (minValue >= 60).yes {
                theDayAcStrengthDurationNum = if (synthesisSevenDaysAcLevel48List.isNotEmpty() && curTimePointIndex > 0) {
                    synthesisSevenDaysAcLevel48List.subList(0, curTimePointIndex)
                        .takeIf { it.isNotEmpty() }
                        ?.map { it.mValue }
                        ?.sum()
                        ?.toLong() ?: 0
                } else {
                    0
                }
            }.otherwise {
                sevenDaysAcLevelNum = if (synthesisSevenDaysAcLevel48List.isNotEmpty() && curTimePointIndex > 0) {
                    synthesisSevenDaysAcLevel48List.subList(0, curTimePointIndex)
                        .takeIf { it.isNotEmpty() }
                        ?.map { it.mValue }
                        ?.sum()
                        ?.toLong() ?: 0
                } else {
                    0
                }
            }
        }

        //7天数据叠加逻辑
        val synthesisSevenDaysAcLevel48AccumulationListTemp = mutableListOf<CusChartData>()
        synthesisSevenDaysAcLevel48List.sortByDescending { it.createdTime }//先降序排列
        if (synthesisSevenDaysAcLevel48List.isNotEmpty()) {
            for (i in synthesisSevenDaysAcLevel48List.indices) {
                // 计算从当前位置到列表末尾所有mValue的总和
                var accumulationValue = 0f
                for (j in i until synthesisSevenDaysAcLevel48List.size) {
                    accumulationValue += synthesisSevenDaysAcLevel48List[j].mValue
                }

                // 创建累积数据，使用当前位置的数据作为模板
                val templateData = synthesisSevenDaysAcLevel48List[i]
                synthesisSevenDaysAcLevel48AccumulationListTemp.add(
                    CusChartData(
                        createdTime = templateData.createdTime,
                        endTime = templateData.endTime,
                        mValue = accumulationValue, // 当前位置及后面所有数据的mValue总和
                        minValue = templateData.minValue,
                        dayNum = templateData.dayNum,
                        exStr = accumulationValue.toInt().toString()
                    )
                )
            }
        }

        synthesisSevenDaysAcLevel48AccumulationListTemp.sortBy { it.createdTime }//还原为升序排列
//        val synthesisSevenDaysAcLevel48AccumulationListStr = JsonUtils.toJson(synthesisSevenDaysAcLevel48AccumulationList)

        //叠加前先算出总和值
        (minValue >= 60).yes {
            sevenDaysAcStrengthDurationNum = if (synthesisTheDayAcLevel48List.isNotEmpty() && curTimePointIndex > 0) {
                synthesisTheDayAcLevel48List.subList(0, curTimePointIndex)
                    .takeIf { it.isNotEmpty() }
                    ?.map { it.mValue }
                    ?.sum()
                    ?.toLong() ?: 0
            } else {
                0
            }
        }.otherwise {
            theDayAcLevelNum = if (synthesisTheDayAcLevel48List.isNotEmpty() && curTimePointIndex > 0) {
                synthesisTheDayAcLevel48List.subList(0, curTimePointIndex)
                    .takeIf { it.isNotEmpty() }
                    ?.map { it.mValue }
                    ?.sum()
                    ?.toLong() ?: 0
            } else {
                0
            }
        }

        val synthesisTheDayAcLevel48ListStr = JsonUtils.toJson(synthesisTheDayAcLevel48List)

        //当天数据叠加逻辑
        synthesisTheDayAcLevel48List.sortByDescending { it.createdTime }//按时间排序（降序）
        val synthesisTheDayAcLevel48AccumulationListTemp = mutableListOf<CusChartData>()

        if (synthesisTheDayAcLevel48List.isNotEmpty()) {
            for (i in synthesisTheDayAcLevel48List.indices) {
                // 如果当前数据的创建时间大于等于当前时间，则跳过该条数据
                if (synthesisTheDayAcLevel48List[i].createdTime >= currentTime) {
                    synthesisTheDayAcLevel48AccumulationListTemp.add(
                        CusChartData(
                            createdTime = synthesisTheDayAcLevel48List[i].createdTime,
                            endTime = synthesisTheDayAcLevel48List[i].endTime,
                            mValue = -1.0f, // 当前位置及后面所有数据的mValue总和
                            minValue = synthesisTheDayAcLevel48List[i].minValue,
                            dayNum = synthesisTheDayAcLevel48List[i].dayNum,
                            exStr = "-1.0"
                        )
                    )
                    continue
                }
                // 计算从当前位置到列表末尾所有mValue的总和
                var accumulationValue = 0f
                for (j in i until synthesisTheDayAcLevel48List.size) {
                    accumulationValue += synthesisTheDayAcLevel48List[j].mValue
                }

                // 创建累积数据，使用当前位置的数据作为模板
                val templateData = synthesisTheDayAcLevel48List[i]
                synthesisTheDayAcLevel48AccumulationListTemp.add(
                    CusChartData(
                        createdTime = templateData.createdTime,
                        endTime = templateData.endTime,
                        mValue = accumulationValue, // 当前位置及后面所有数据的mValue总和
                        minValue = templateData.minValue,
                        dayNum = templateData.dayNum,
                        exStr = accumulationValue.toInt().toString()
                    )
                )
            }
        }
        synthesisTheDayAcLevel48AccumulationListTemp.sortBy { it.createdTime }//还原为升序排列
        val synthesisTheDayAcLevel48AccumulationListStr = JsonUtils.toJson(synthesisTheDayAcLevel48AccumulationListTemp)

        //有效天数
        var validDays = 0

        // 遍历sevenDaysAcLevel48Pairs，检查每天的数据
        sevenDaysAcLevel48Pairs.forEach { dayPair ->
            val dayData = dayPair.second // 获取当天的List<CusChartData>

            // 检查当天是否有任意一个CusChartData的mValue大于0
            val hasAnyValueGreaterThanZero = dayData.isNotEmpty() && dayData.any { it.mValue > 0 }

            if (hasAnyValueGreaterThanZero) {
                validDays++
            }
        }

        //7天数据区间再除以有效天数均化
        synthesisSevenDaysAcLevel48AccumulationListTemp.forEach {beanIt->
            beanIt.mValue = MathUtil.div(beanIt.mValue.toString(), validDays.toString(),false).toFloat()
        }

        //7天数据再除以有效天数均化
        sevenDaysAcConsumption = MathUtil.div(synthesisSevenDaysAcLevel48List.sumOf { it.mValue.toInt()}.toString(),validDays.toString(),false).toFloat().toLong()

        //获取当天和7天里的最大值
        val synthesisTheDayMaxTemp = ((synthesisTheDayAcLevel48AccumulationListTemp.maxOfOrNull { it.mValue } ?: 100f).toFloat())+20f
        val synthesisSevenDaysMaxTemp = ((synthesisSevenDaysAcLevel48AccumulationListTemp.maxOfOrNull { it.mValue } ?: 100f).toFloat())+20f
        synthesisTheDayAcLevel48AccumulationListTemp.forEach { theDayBeanIt->
            (theDayBeanIt.mValue>0).yes { theDayBeanIt.mValue = (MathUtil.div(theDayBeanIt.mValue.toString(),(if (synthesisSevenDaysMaxTemp>synthesisTheDayMaxTemp) synthesisSevenDaysMaxTemp else synthesisTheDayMaxTemp).toString(),false).toFloat() * 100) }
        }
        synthesisSevenDaysAcLevel48AccumulationListTemp.forEach { sevenDaysBeanIt->
            sevenDaysBeanIt.mValue = (MathUtil.div(sevenDaysBeanIt.mValue.toString(),(if (synthesisSevenDaysMaxTemp>synthesisTheDayMaxTemp) synthesisSevenDaysMaxTemp else synthesisTheDayMaxTemp).toString(),false).toFloat() * 100)
        }

        val synthesisTheDayAcLevel48AccumulationListStr2 = JsonUtils.toJson(synthesisTheDayAcLevel48AccumulationListTemp)
        val synthesisSevenDaysAcLevel48AccumulationListStr2 = JsonUtils.toJson(synthesisSevenDaysAcLevel48AccumulationListTemp)

        (minValue >= 60).yes {
            synthesisTheDayAcStrengthDuration48AccumulationList.clear()
            synthesisTheDayAcStrengthDuration48AccumulationList.addAll(synthesisTheDayAcLevel48AccumulationListTemp)
            synthesisSevenDaysAcStrengthDuration48AccumulationList.clear()
            synthesisSevenDaysAcStrengthDuration48AccumulationList.addAll(synthesisSevenDaysAcLevel48AccumulationListTemp)
        }.otherwise {
            synthesisTheDayAcLevel48AccumulationList.clear()
            synthesisTheDayAcLevel48AccumulationList.addAll(synthesisTheDayAcLevel48AccumulationListTemp)
            synthesisSevenDaysAcLevel48AccumulationList.clear()
            synthesisSevenDaysAcLevel48AccumulationList.addAll(synthesisSevenDaysAcLevel48AccumulationListTemp)
        }

    }

    /**
     * 根据当前时间戳计算对应的数据点索引
     * @return
     */
    private fun calculateCurrentTimePointIndex(): Int {
        val calendar = Calendar.getInstance()
        val currentHour = calendar.get(Calendar.HOUR_OF_DAY)
        val currentMinute = calendar.get(Calendar.MINUTE)

        // 计算当前时间对应的30分钟区间索引
        // 每小时有2个数据点（00:00, 00:30），总共48个点
        return  currentHour * 2 + if (currentMinute >= 30) 1 else 0
    }
}